package com.sayice.icemusic.util.encrypt;

import com.sayice.icemusic.util.encrypt.AESUtils;
import com.sayice.icemusic.util.encrypt.RSAUtils;

import java.util.HashMap;

/**
 * 网易云音乐参数加密算法
 *
 * @author shubing
 */
public class CloudEncrypt {
    private static final String MODULUS = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7";
    private static final String NONCE = "0CoJUm6Qyw8W8jud";
    private static final String IV0 = "0102030405060708";
    private static final String PUB_KEY = "010001";
    
    /**
     * 网易云音乐参数加密
     *
     * @param params 待加密参数
     */
    public static HashMap<String, String> encrypt(String params) {
        String secKey = createSecretKey(16);
        String encText = AESUtils.encrypt(AESUtils.encrypt(params, NONCE, IV0), secKey, IV0);
        String encSecKey = RSAUtils.encrypt(secKey, PUB_KEY, MODULUS);
        HashMap<String, String> data = new HashMap<>(4);
        data.put("params", encText);
        data.put("encSecKey", encSecKey);
        return data;
    }
    
    /**
     * 创建密钥
     *
     * @param size 位数
     * @return 指定位数的密钥字符串
     */
    private static String createSecretKey(int size) {
        final String keys = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder keyBuilder = new StringBuilder();
        for (int i = 0; i < size; i++) {
            int pos = (int) Math.floor(Math.random() * keys.length());
            keyBuilder.append(keys.charAt(pos));
        }
        return keyBuilder.toString();
    }
}
